package com.project.controller;

import com.alibaba.fastjson.JSONObject;
import com.project.bean.UserBean;
import com.project.bean.UserResultBean;
import com.project.dto.UserDto;
import com.project.dto.UserResultDto;
import com.project.service.IUserResultService;
import com.project.service.IUserService;
import com.rabbitmq.client.Channel;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserResultService userResultService;
    
    @RequestMapping("login")
    public UserBean login(String userName, String password, HttpServletRequest request) throws NoSuchAlgorithmException {
//        UserBean user= userService.login(userNum, MD5Encryptor.encrypt(password));
//        ResultVo resultVO =new ResultVo();
//        if(null!=user) {
//            request.getSession().setAttribute("user",user);
//            //把对象转换为json
//            String json = JSON.toJSONString(user);
//            //生成Token
//            String token = CreateToken.createToken(json);
//            resultVO.setTag(0);
//            resultVO.setJson(token);
//        }else {
//            resultVO.setTag(1);
//            resultVO.setJson("");
//        }
        Md5Hash md5Hash = new Md5Hash(password);
        UserBean user = userService.login(userName,md5Hash.toHex());
        if (user != null) {
            request.getSession().setAttribute("loginUser", user);
        }
        return user;
    }
    
    @RequestMapping("findMoney")
    public Double findMoney(HttpServletRequest request) {
        UserBean userBean = (UserBean) request.getSession().getAttribute("loginUser");
        return userService.findMoney(userBean.getUserNum());
    }
    
    @RequestMapping("getLoginUser")
    public UserBean getLoginUser(HttpServletRequest req) {
        return (UserBean) req.getSession().getAttribute("loginUser");

    }

    @RequestMapping("getUser/{userNum}")
    public UserBean getUser(@PathVariable("userNum") Long userNum) {
        return userService.findUserNum(userNum);
    }
    @RequestMapping("delLoginUser")
    public String  delLoginUserr(HttpServletRequest req) {
        req.getSession().setAttribute("loginUser", null);
        return"ok";
    }
    
    @RequestMapping("addUser")
    public String addUser(UserBean userBean) throws NoSuchAlgorithmException {
        UserBean user = userService.addUser(userBean);
        if (user == null) {
            return "ok";
        } else {
            return "no";
        }
        
    }
    
    @RequestMapping("updateUser")
    public String updateUser(String company,String IDImg, String quaImg,HttpServletRequest request) throws InterruptedException {
        UserBean user1=(UserBean) request.getSession().getAttribute("loginUser");
        UserDto userDto=new UserDto();
        userDto.setUserNum(user1.getUserNum());//临时的登录用户编号
        //将获取的公司名、图片封装到对象
        userDto.setCompany(company);
        userDto.setQuaImg(quaImg);
        userDto.setIDImg(IDImg);
        user1.setIDImg(IDImg);
        user1.setQuaImg(quaImg);
        user1.setCompany(company);
        userService.updateUser(user1);
        //根据登录用户查询出该用户的其他信息
        UserBean userBean=userService.findUserNum(userDto.getUserNum());
        userDto.setUserName(userBean.getUserName());
        userDto.setPhone(userBean.getPhone());
        userDto.setPassword(userBean.getPassword());
        userDto.setSex(userBean.getSex());
        userDto.setRealName(userBean.getRealName());
       
        //将封装好的dto发给到审核系统MQ进行审核
        //创建关联数据对象
//        CorrelationData correlationData=new CorrelationData(userDto.getUserNum());
        //把对象转化成json对象
        String jsonString = JSONObject.toJSONString(userDto);
        //发送到MQ
        rabbitTemplate.convertAndSend("directExchangeUser","rabbit.authentication",jsonString);
        Thread.sleep(200);
//        userService.updateUser(user);
        //发送成功 将资料认证状态改为 1--审核中
        userService.updateStatus(userDto.getUserNum(),1);
        return "ok";
    }
    
    @RequestMapping("updateCustomtStatus/{status}/{userNum}")
    public String  updateCustomtStatus(@PathVariable("status") int status, @PathVariable("userNum")String userNum){
        userService.updateCustomtStatus(status,Long.valueOf(userNum));
        return "ok";
    }
    @RabbitListener(queues = "UserVerifyResult")
    public void getUserResult(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, String json) throws IOException {
        System.out.println("用户审核"+json);
        //把JSon转换为对象
        if (StringUtils.hasLength(json)) {
            UserResultDto userResultDto =
                    JSONObject.parseObject(json, UserResultDto.class);
            UserResultBean resultBean=new UserResultBean(userResultDto.getUserNum(),userResultDto.getResult(),userResultDto.getReason());
            userResultService.add(resultBean);
            if (userResultDto.getResult() == 1) {//审核通过
                //认证成功 将资料认证状态改为 0--审核完成
                userService.updateStatus(userResultDto.getUserNum(), 0);
                
            }
            if (userResultDto.getResult()==2){
                //认证成功 将资料认证状态改为 0--审核完成
                userService.updateStatus(userResultDto.getUserNum(), 2);
            }
            channel.basicAck(tag, false); //tag标志，false-不批量确认
        }
        
    }
}
